#!/bin/bash
. ./lib

options=()
options+=("Edit IPv4" "/etc/iptables/iptables.rules")
options+=("Edit IPv6" "/etc/iptables/ip6tables.rules")
options+=("" "")
options+=("Load Rules" "iptables-restore & ip6tables-restore")
options+=("" "")
options+=("Start At Boot" "systemctl enable iptables & systemctl enable ip6tables")
options+=("Generate Default Rules" "/etc/iptables/iptables.rules & /etc/iptables/ip6tables.rules")

defaultitem=""
sel=$(whiptail --backtitle "$apptitle" --title "Firewall Menu :" --menu "" --default-item "$defaultitem" --cancel-button "Back" 0 0 0 \
  "${options[@]}" \
  3>&1 1>&2 2>&3)
if [ ! "$?" = "0" ]; then
  exit 1
fi
sed -i "/^defaultitem=/c\defaultitem=\"$sel\"" $0

case $sel in
		'Edit IPv4') editfile /etc/iptables/iptables.rules;;
		'Edit IPv6') editfile /etc/iptables/ip6tables.rules;;
		'Load Rules') iptables-restore < /etc/iptables/iptables.rules
		              ip6tables-restore < /etc/iptables/ip6tables.rules;;
		'Start At Boot') systemctl enable iptables
		                 systemctl start iptables
		                 systemctl enable ip6tables
		                 systemctl start ip6tables;;
		'Generate Default Rules')
		   file=/etc/iptables/iptables.rules
		   echo '*filter' > $file
		   echo ':INPUT DROP [0:0]' >> $file
		   echo ':FORWARD DROP [0:0]' >> $file
		   echo ':OUTPUT ACCEPT [0:0]' >> $file
		   echo '-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT' >> $file
		   echo '-A INPUT -i lo -j ACCEPT' >> $file
		   echo '# SSH' >> $file
		   echo '#-A INPUT -p tcp -m tcp --dport 22 -m state --state NEW -j ACCEPT' >> $file
		   echo '# Ping' >> $file
		   echo '#-A INPUT -p icmp -j ACCEPT' >> $file
		   echo '# SNMP' >> $file
		   echo '#-A INPUT -s 192.168.0.0/24 -p udp -m udp --dport 161 -m state --state NEW -j ACCEPT' >> $file
		   echo 'COMMIT' >> $file
		   iptables-restore $file
		   file=/etc/iptables/ip6tables.rules
		   echo '*filter' > $file
		   echo ':INPUT DROP [0:0]' >> $file
		   echo ':FORWARD DROP [0:0]' >> $file
		   echo ':OUTPUT ACCEPT [0:0]' >> $file
		   echo '-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT' >> $file
		   echo '-A INPUT -i lo -j ACCEPT' >> $file
		   echo 'COMMIT' >> $file
		   ip6tables-restore $file;;
esac

exit 0
